﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class JsonArrayToNullConverter : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            var canConvert = objectType.IsArray || (objectType.IsGenericType && objectType.GetGenericTypeDefinition().IsAssignableFrom(typeof(IEnumerable<>)));
            return canConvert;
        }

        public override bool CanRead => false;

        public override bool CanWrite => true;

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var enumerator = (IEnumerable)value;

            if (enumerator != null && enumerator.GetEnumerator().MoveNext() == false)
            {
                writer.WriteNull();
                return;
            }
            serializer.Serialize(writer, value);
        }
    }
}

